#include "objectcounterdlg.h"
#include "countresitem.h"
#include "ui_objectcounterdlg.h"
#include <qthread.h>

ObjectCounterDlg::ObjectCounterDlg(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ObjectCounterDlg)
{
    ui->setupUi(this);
    setWindowFlags(Qt::Window /*| Qt::WindowStaysOnTopHint*/);
    setAttribute(Qt::WA_DeleteOnClose); // 确保窗口关闭时对象销毁
    setWindowTitle("物体计数");
    m_cntThread = std::make_unique<CounterThread>(&m_counter);
    connect(&m_counter, &CvUtils::objectCounter::reCounted, this ,&ObjectCounterDlg::process, Qt::QueuedConnection);
}

ObjectCounterDlg::~ObjectCounterDlg()
{
    m_cntThread.reset();
    delete ui;
}

void ObjectCounterDlg::showCountRes(const char* imagePath) {
    m_background = QPixmap(QString::fromLocal8Bit(imagePath));

    if (m_background.isNull())  {
        qWarning() << "图片加载失败:";
        return;
    }

    QGraphicsScene* scene = ui->Preview->scene();
    if (!scene) {
        scene = new QGraphicsScene(this);
        ui->Preview->setScene(scene);
    }

    scene->setSceneRect(m_background.rect());
    scene->addPixmap(m_background)->setZValue(-1);

    // 调整视图
    ui->Preview->fitInView(scene->itemsBoundingRect(),
                               Qt::KeepAspectRatio);

    // 5. 触发计数
    cv::Mat image = cv::imread(imagePath);
    if (!image.empty())  {
        emit m_counter.sig_initImage(image);
        emit m_counter.sig_reCount();
    }
}

void ObjectCounterDlg::process(const ObjectInfo& objInfo)
{
    //qDebug() << "Radius values:" << objInfo.rMap;
    qDebug() <<"收到reCounted信号";
    cv::TickMeter tm;
    tm.start();

    QGraphicsScene* scene = ui->Preview->scene();
    scene->clear();
    scene->addPixmap(m_background)->setZValue(-1);

    // 添加总数显示
    ui->NumLabel->setNum(objInfo.total);

    // 为每个物体创建独立的CountResItem
    for (size_t i = 0; i < objInfo.total;  ++i) {
        CountResItem* item = new CountResItem(
            i + 1, // ID从1开始
            objInfo.positionMap[i],
            objInfo.rMap[i]
            );
        item->setZValue(1);
        scene->addItem(item);
    }

    // 调整视图
    if (!objInfo.positionMap.empty())  {
        ui->Preview->fitInView(scene->itemsBoundingRect(),
        Qt::KeepAspectRatio);
    }

    //缓存结果
    if(!m_objInfoCached[ui->comboBox->currentIndex()].first){
        m_objInfoCached[ui->comboBox->currentIndex()] = std::make_pair(true, objInfo);
    }

    tm.stop();
    qDebug()<<"ObjectCounterDlg::process:"<<tm.getTimeMilli()<<"ms";
}

void ObjectCounterDlg::on_comboBox_activated(int index)
{
    if(m_objInfoCached[index].first == true){//命中缓存
        process(m_objInfoCached[index].second);
        return;
    }
    emit m_counter.sig_setMarkType(static_cast<CvUtils::markType>(index));
}


CounterThread::CounterThread(CvUtils::objectCounter *counter)
{
    _cnt_thread = new QThread();
    counter->moveToThread(_cnt_thread);
    QObject::connect(_cnt_thread, &QThread::finished, _cnt_thread, &QObject::deleteLater);
    _cnt_thread->start();
}

CounterThread::~CounterThread()
{
    _cnt_thread->quit();
}
